from django.core.management.base import BaseCommand
from cmdb.models import UserGroup, UserRole

class Command(BaseCommand):
    help = '初始化用户组和角色数据'

    def handle(self, *args, **options):
        # 创建用户组
        groups = {
            'dev': '开发组',
            'ops': '运维组',
            'test': '测试组',
            'product': '产品组',
        }
        
        created_groups = {}
        for code, name in groups.items():
            group, created = UserGroup.objects.get_or_create(
                code=code,
                defaults={'name': name}
            )
            created_groups[code] = group
            if created:
                self.stdout.write(self.style.SUCCESS(f'创建用户组: {name}'))
            else:
                self.stdout.write(self.style.WARNING(f'用户组已存在: {name}'))
        
        # 为每个组创建角色
        roles = {
            'dev': [
                {'name': '开发工程师', 'level': 1},
                {'name': '开发组长', 'level': 2},
                {'name': '开发总监', 'level': 3},
            ],
            'ops': [
                {'name': '运维工程师', 'level': 1},
                {'name': '运维组长', 'level': 2},
                {'name': '运维总监', 'level': 3},
            ],
            'test': [
                {'name': '测试工程师', 'level': 1},
                {'name': '测试组长', 'level': 2},
                {'name': '测试总监', 'level': 3},
            ],
            'product': [
                {'name': '产品经理', 'level': 1},
                {'name': '产品组长', 'level': 2},
                {'name': '产品总监', 'level': 3},
            ],
        }
        
        for group_code, role_list in roles.items():
            group = created_groups.get(group_code)
            if not group:
                self.stdout.write(self.style.ERROR(f'找不到用户组: {group_code}'))
                continue
                
            for role_data in role_list:
                role, created = UserRole.objects.get_or_create(
                    group=group,
                    level=role_data['level'],
                    defaults={'name': role_data['name']}
                )
                
                if created:
                    self.stdout.write(self.style.SUCCESS(f'创建角色: {role.name} (组: {group.name})'))
                else:
                    self.stdout.write(self.style.WARNING(f'角色已存在: {role.name} (组: {group.name})'))
        
        self.stdout.write(self.style.SUCCESS('初始化用户组和角色数据完成')) 